/*=========================================================================
project:       Electing Peace
Author:        Aila Matanock
Dependencies:  UC Berkeley
---------------------------------------------------------------------------
Creation Date: 2012      
Modification Date: 7/28/2017   
Do-file version: 5   
References: Initial data universe drawn from UCDP Peace Agreement Dataset (modified) and UCDP Conflict Termination Dataset (also modified)
Master data are in F1975Bookmergedplus@5.dta, Base_Data_Rerun June 17 Update@1.dta, and postconflict_elections_legislative_merged.dta (posted versions including needed variables are noted in code as needed)
Output: Models and graphs
===========================================================================*/


*==========================================================================*
*===============================Chapter 1==================================*
*==========================================================================*

use Matanock_Electing Peace_Agreements.dta


*==================Figure 1.1 Peace Agreements over Time by Type

gen dum=1

twoway histogram payear if dum, start(1975) width(1) freq bfcolor(none) blcolor(black) || histogram payear if propartNC, freq start(1975) width(1) barw(.8) bfcolor(gray) blcolor(black) legend(order(1 "All Agreements" 2 "Electoral Participation Provisions") pos(2) ring(0) col(1)) xlabel(1975(5)2005) xtitle("Year") ytitle("Peace Agreements (Count)")



*==========================================================================*
*===============================Chapter 3==================================*
*==========================================================================*


*==================Figure 3.1 Peace Agreements over Time

histogram payear if dum, start(1975) width(1) gap(55) freq bfcolor(black) blcolor(none) legend(order(1 "All Agreements") pos(2) ring(0) col(1)) xlabel(1975(5)2005) xtitle("Year") ytitle("Peace Agreements")


*==================Figure 3.2 International Election Observation over Time

preserve

*use NELDA_1945-2010.dta [DATA FOR THE FOLLOWING FIGURES NOT POSTED BUT AVAILABLE FROM THE AUTHOR UPON REQUEST]

encode types, generate(ntypes)
encode nelda45, generate(observed)

replace observed=0 if observed==2
replace observed=0 if observed==1
*These two are "N/A"
replace observed=1 if observed==4
replace observed=. if observed==3
*These are "unclear"

gen elec=1
tostring ccode, replace
tostring year, replace
generate cowid_date=ccode+"_"+year
by cowid_date, sort: egen elecmon=max(observed)
*This means that there are a handful of elections in which an election aside from the legislative election is observed, and the legistlative election itself is not, but I count both (and not doing so actually strengthens my results).
*Keep parliamentary and legislative elections only
keep if ntypes==3

#drop duplicates (from Hyde)
generate NELDAyear=substr(electionid, 5, 4)
generate NELDAmmdd=substr(electionid, 10, 4)
generate NELDAround=substr(electionid, 16, 1)
generate NELDAccode=substr(electionid, 1, 3)
generate NELDAtype=substr(electionid, 15, 1)

move NELDAccode electionid
move NELDAyear electionid
move NELDAmmdd electionid
move NELDAround electionid
move NELDAtype electionid

duplicates tag NELDAmmdd NELDAccode NELDAyear NELDAround, generate(samedaydupes)
gsort samedaydupes -NELDAtype
generate electionid2=""
replace electionid2=electionid if samedaydupes==0
replace electionid2=NELDAccode+"-"+NELDAyear+"-"+NELDAmmdd+"-"+"G"+NELDAround if samedaydupes==1
replace electionid=NELDAccode+"-"+NELDAyear+"-"+NELDAmmdd+"-"+NELDAtype+NELDAround

duplicates drop electionid2, force

by cowid_date, sort: egen mmmdd=min(mmdd)
keep if mmdd==mmmdd

keep cowid_date ccode year elecmon elec

rename elec delec
rename elecmon delecmon
by year, sort: egen elec=sum(delec)
by year, sort: egen elecmon=sum(delecmon)
gen pelecmon=elecmon/elec

sort year
quietly by year:  gen dup = cond(_N==1,0,_n)
drop if dup>1
destring year, replace
drop if year<1960
drop if year>2010

graph twoway bar pelecmon year, color(black) barwidth(.4) xlabel(1960(5)2010) ylabel(0(.1).9) xtitle("Year") ytitle("International Election Observation" "(Percentage of Elections)")
restore


*==================Figure 3.3 International Election Observation over Time by Region

preserve

*use NELDAALLR.dta [DATA FOR THE FOLLOWING FIGURES NOT POSTED BUT AVAILABLE FROM THE AUTHOR UPON REQUEST]
*Uses data from Hyde and Marinov 2012 (not posted).
*These are data in which averages are by region - already generated in prior code.

split reg_year, generate(region) parse(_)
rename region1 region
rename region2 payear
destring payear, replace
destring region, replace
drop if payear<1960

twoway (lowess pelecmon payear if region==1) (lowess pelecmon payear if region==2)(lowess pelecmon payear if region==3)(lowess pelecmon payear if region==4)(lowess pelecmon payear if region==5), xlabel(1960(5)2005) xtitle("Year") ytitle("International Election Observation" "(Percent of Elections, Lowess Smoothed)") legend(label(1 Europe) label(2 Asia) label(3 Americas) label(4 MENA) label(5 Africa))
restore


*==================Figure 3.4 Democracy and Governance Aid over Time

preserve

*use FINKELETAL2008.dta [DATA FOR THE FOLLOWING FIGURES NOT POSTED BUT AVAILABLE FROM THE AUTHOR UPON REQUEST]
*Uses data from Finkel et al. 2008 (not posted).

split cowid_ldate, generate(year) parse(_)

rename year1 ccode2
rename year2 year
destring year, replace
by year, sort: egen said100=sum(aid100)
by year, sort: egen said000=sum(aid000)
by year, sort: egen soda100=sum(oda100)
by year, sort: egen soda000=sum(oda000)
sort year
quietly by year, sort:  gen dup = cond(_N==1,0,_n)
tab dup
drop if dup>1
drop dup 
gen natdg=(said100+soda100)/(said100+soda100+said000+soda000)
drop if year < 1990
drop if year > 2004

graph twoway bar natdg year, color(black) barwidth(.5) xlabel(1990(2)2004) xtitle("Year") ytitle("Democracy and Governance Aid" "(Percentage of Development Assistance)")  
restore


*==================Figure 3.5 Democracy and Governance Aid over Time by Region

preserve

*use FINKELETAL2008R.dta [DATA FOR THE FOLLOWING FIGURES NOT POSTED BUT AVAILABLE FROM THE AUTHOR UPON REQUEST]
*Uses data from Finkel et al. 2008 (not posted).

split reg_lyear, generate(region) parse(_)
rename region1 region
rename region2 payear
destring payear, replace
destring region, replace

twoway (lowess regdg payear if region==1) (lowess regdg payear if region==2)(lowess regdg payear if region==3)(lowess regdg payear if region==4)(lowess regdg payear if region==5), xlabel(1990(5)2005) xtitle("Year") ytitle("Democracy and Governance Aid" "(Percent of Development Assistance, Lowess)") legend(label(1 Europe) label(2 Aisa) label(3 Americas) label(4 MENA) label(5 Africa))
restore


*==================Figure 3.6 International Election-Related Aid Reactions

preserve

*use NELDA_1945-2010.dta [DATA FOR THE FOLLOWING FIGURES NOT POSTED BUT AVAILABLE FROM THE AUTHOR UPON REQUEST]
*Uses data from Hyde and Marinov 2012 (not posted).

encode nelda57, generate(threats)

replace threats=0 if threats==2
replace threats=0 if threats==1
*These two are "N/A"
replace threats=1 if threats==4
replace threats=. if threats==3
*These are "unclear"

drop if year<1960
drop if year>2010

twoway histogram year if threats, start(1960) width(.3) gap(30) freq bfcolor(black) blcolor(black) xlabel(1960(5)2010) xtitle("Year") ytitle("Threats of Acts to Reduce Aid Related to" "Elections (Potentially Violations)")
restore



*==========================================================================*
*===============================Chapter 4==================================*
*==========================================================================*


*==================Table 4.1 Electoral Participation Provisions with Expectations of External Engagement

tab coldwar propartNC, chi2 exact

gen nexlemd=0
replace nexlemd=1 if nexlem>0.7321429
tab nexlemd propartNC, chi2 exact

gen regdgd=0
replace regdgd=1 if regdg>0.0675402
replace regdgd=. if regdg==.
tab regdgd propartNC, chi2 exact


*==================Table 4.2 Inclusion of Electoral Participation Provisions in Peace Agreements

*Model 1
logit propartNC coldwar nexlem, cluster(ccode)

*Model 2
logit propartNC regdg, cluster(ccode)

*Model 3
logit propartNC coldwar oild milaidd colbrit colfra, cluster(ccode)

*Model 4
logit propartNC coldwar nexlem oild milaidd colbrit colfra, cluster(ccode)

*Model 5
logit propartNC coldwar regdg oild milaidd colbrit colfra, cluster(ccode)

*Average Marginal Effects
quietly logit propartNC coldwar nexlem oild milaidd colbrit colfra, cluster(ccode) nolog
margins, dydx(nexlem oild milaidd colbrit colfra)


*==================Table 4.3 Implementation of Electoral Participation Provisions in Peace Agreements

*Model 1i
logit proapart coldwar nexlem, cluster(ccode)

*Model 2i
logit proapart coldwar regdg, cluster(ccode)

*Model 3i
logit proapart coldwar oild milaidd colbrit colfra, cluster(ccode)

*Model 4i
logit proapart coldwar nexlem oild milaidd colbrit colfra, cluster(ccode)

*Model 5i 
logit proapart coldwar regdg oild milaidd colbrit colfra, cluster(ccode)

*Average Marginal Effects
quietly logit proapart coldwar nexlem oild milaidd colbrit colfra, cluster(ccode) nolog
margins, dydx(nexlem oild milaidd colbrit colfra)

************Switch dataset************

use Matanock_Electing Peace_Conflicts.dta, clear

replace outcome_a_first=0 if outcome_a_first==.
gen keepobs=1 if payear >=1975 & payear<=2005
drop if altcensor1==1

sort iden payear

*bys iden: gen duration = _n
gen logdur = log(duration)
gen duration2 = duration^2
gen duration3 = duration^3 

duplicates list ccode payear nsideb outcome_a_first

list ccode payear nsideb outcome_a_first duration if ccode == 700 &  payear== 1993 & nsideb=="Hizb-i Islami-yi Afghanistan - Hekmatyar faction"
list ccode payear nsideb outcome_a_first duration if ccode == 437 &  payear== 2003 & nsideb=="MPIGO"
list ccode payear nsideb outcome_a_first duration if ccode == 437 &  payear== 2003 & nsideb=="MJP"


*Drop the ones with the lowest duration: 
drop in 3
drop in 7
drop in 8

cap drop lrebest
gen lrebest=ln(rebest1)


*==================Table 4.4 Conflict Termination through Electoral Participation Provisions

*Model 6 
mlogit outcome_a_first coldwar nexlem duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)

*Model 7 
mlogit outcome_a_first coldwar regdg duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)

*Model 8 
mlogit outcome_a_first coldwar oild milaidd colbrit colfra duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)

*Model 9
mlogit outcome_a_first coldwar nexlem oild milaidd colbrit colfra duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)

*Model 10
mlogit outcome_a_first coldwar regdg oild milaidd colbrit colfra duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)

*Average Marginal Effects
mlogit outcome_a_first coldwar nexlem oild milaidd colbrit colfra duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)rrr

*==================Figure 4.1 Predicted Probability of Conflict Termination through Electoral 

preserve

	mlogit outcome_a_first coldwar nexlem oild milaidd colbrit colfra duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)

	margins, at(nexlem==(0(.1)1) (median) coldwar oild milaidd colbrit colfra) predict(outcome(8)) atmeans vsquish post

	mat drop _all
	mat t=J(11,3,.)
	
	/* get the 11 "at" values    */
	mat a = (0\0.1\0.2\0.3\0.4\0.5\0.6\0.7\0.8\0.9\1)                        
		forvalues i=1/11 {
		  * get probability estimates 
		  mat t[`i',1] = _b[`i'._at]  
		  * compute lower limit       
		  mat t[`i',2] = _b[`i'._at] - 1.96*_se[`i'._at] 
		  * compute upper limit
		  mat t[`i',3] = _b[`i'._at] + 1.96*_se[`i'._at]   
		}
	
	* Predicted probabilities 
	*Computes and stores the predicted probs (AT THOSE SPECIFIC VALUES OF NEXLEM -- 0.1 0.2 0.3 ...)
	
	cap mat drop t tmp sv
	mat t=t,a            
	mat colnames t = prob ll ul at                     
	svmat t, names(col)                                
	matrix tmp = r(table) 
	matrix sv = nullmat(sv) , tmp[1..4,1...] 
		
	twoway (rarea ll ul at, bcolor(gs13))(line prob at, lcolor(ebblue) lwidth(medthick)), legend(off) xtitle(nexlem) ytitle(Predicted Probability) title(Predicted probability for electoral provisions)

restore
	
*Must install spost package (spost13 and spost9_legacy) to run. 
*The loop then estimates the predicted probability for each outcome at the median of all variables except the one that we are looping over (which is either = 0 or = 1), and then computes the difference in the predicted probabilities, as well as a confidence intervals. 

mat drop _all

local inds coldwar nexlem oild milaidd colbrit colfra
local z=0

foreach var of local inds{
	local ++z
	matrix A`var' = J(6,1,`z')
	mlogit outcome_a_first coldwar nexlem oild milaidd colbrit colfra duration duration2 duration3 if keepobs==1, robust cluster(ccode) base(0)
	quietly prvalue, x(`var'=0) rest(median) save
	prvalue, x(`var'=1) rest(median) diff
	mat B`var' = r(pred)
	mat a = nullmat(a) \ A`var', B`var'
}

preserve
	drop _all
	mat colnames a = Variable PredProb LowerBound UpperBound Category SE z_score
	svmat a, n(col)
	lab def Variable 1"coldwar" 2"nexlem" 3"oild" 4"milaidd" 5"colbrit" 6"colfra" 
	lab val Variable Variable
	order Variable Category PredProb LowerBound UpperBound SE z_score
	export excel using "predicted_probs_difference.xls", sheetmodify sheet(desc) firstrow(var)
restore

*Part B created in Excel


*==================Figure 4.2 Militant Group Vote Share in the Election after Peace 
*=============================Agreements with Participation Provisions

*Created in Excel


*==================Table 4.6 Correlation between Electoral Participation Provisions and Other 
*============================Substantive Provisions in the Peace Agreement

use Matanock_Electing Peace_Agreements.dta clear

corr propartNC  cease ssr ddr withd mil_prov pp intgov intciv elections interim natalks sharegov pol_prov aut fed ind ref shaloc regdev cul demarcation locgov terr_prov amn pris recon justice_prov reaffirm outlin pko co_impl



*==========================================================================*
*===============================Chapter 6==================================*
*==========================================================================*


*=======Table 6.1. Cases with Electoral Participation Provisions May Be Harder to Settle=======* 

ttest ltot, by(propart) 
ttest rgdpch7, by(propart)
ttest lmtnest, by(propart)
ttest contraband, by(propart)


*=======Table 6.2. Conflict Recurrence after Peace Agreements, 1975-2005=======* 

tab failure propart, exact 


*=======Table 6.3. Participation Provisions and Conflict Recurrence=======* 

*Model 1
logit failure propart, cluster(ccode)

*Model 2
logit failure propart ddr ssr intgov intciv, cluster(ccode)

*Model 3
logit failure propart cumint mgduration rgdpch7 balance1, cluster(ccode)

*Model 4
logit failure propart pastagree nosignfac pafacnum morenegs, cluster(ccode)

*Model 5
logit failure propart terr identity1 kbmarx totalg, cluster(ccode)

*Model 6
logit failure propart rgdpch7 coldwar p911 unpkIN nexlem regdemo_p polity2 pop_penn, cluster(ccode)

*Model 7
logit failure propart rgdpch7 polity2 pop_penn, cluster(ccode)

*Model 8
logit failure propart i.region##i.yrdum, cluster(ccode)

*Model 9
logit failure propart ddr ssr cumint mgduration rgdpch7 pafacnum morenegs terr totalg unpkIN regdemo pop_penn i.region##i.yrdum, cluster(ccode)


*=======Figure 6.1. Peace Endurance across Peace Agreements (Kaplan-Meier Estimates)=======*

replace f10 = 0 if f10==1 & censored == 1

stset mbreak, failure(f10)
stdes

su mbreak, d

sts graph, survival by(propartNC) title("") ytitle(Survival of Peace) xtitle(Months after the Peace Agreement) legend(size(small) label(1 "Without Participation Provisions") label(2 "With Participation Provisions") ring(1))


*=======Table 6.4. Electoral Participation Provisions, Conditioned on Expectations=======* 
*=======of External Engagement, and Conflict Recurrence

*Model 10
logit failure propart##c.nexlem, cluster(ccode)

*Model 11
logit failure propart##c.nexlem i.region##i.yrdum, cluster(ccode)

*Model 12
logit failure propart##c.regdg, cluster(ccode)

*Model 13
logit failure propart##c.regdg i.region##i.yrdum, cluster(ccode)


*=======Figure 6.2. Predicted Probabilities of Conflict Recurrence=======*

*Regional Election Observation (Percent, Lagged)
logit failure propart##c.nexlem, cluster(ccode)
quietly margins, at(nexlem==(0(.1)1)) over(propart)
marginsplot, l(90) title("") xtitle("Regional Percent of Elections Observed (Lagged)") ytitle("Probability of Conflict Recurrence (5 Years)") plot2opts(msymbol(D)) legend(size(3)) addplot(histogram nexlem, below fraction fintensity(inten10) lcolor(white) fcolor(eltblue) legend(order(1 "90% confidence intervals" 3 "Without Participation Provisions" 4 "With Participation Provisions" 5 "Fraction of Observations") size(3))) scheme(s1mono)

*Regional Democracy and Governance Assistance (Percent Development Aid, Lagged 2-Year Average
logit failure propart##c.regdg, cluster(ccode)
quietly margins, at(regdg==(0(0.01)0.20)) over(propart)
marginsplot, l(90) title("") xtitle("Regional Democracy and Governance Assistance""Percent Development Aid, Lagged 2-Year Avg.") ytitle("Probability of Conflict Recurrence (5 Years)") plot2opts(msymbol(D)) legend(size(3)) addplot(histogram regdg, fraction fintensity(inten10) lcolor(white) fcolor(eltblue) legend(order(1 "90% confidence intervals" 3 "Without Participation Provisions" 4 "With Participation Provisions" 5 "Fraction of Observations") size(3)) below) scheme(s1mono)


*=======Table 6.5. Different Measures of Conflict Recurrence after Peace Agreements=======*

tab ended propart, exact
tab dyvi05 propart, exact
tab anyh5 propart, exact


*=======Table 6.6. Conflict Recurrence after Peace Agreements 1975-2005=======*

replace proapart=. if propart==.
tab failure proapart, exact


*=======Table 6.7. External Engagement in First Post-Conflict Elections=======*

*use postconflict_elections_legislative_merged.dta, clear [DATA FOR THE FOLLOWING FIGURES NOT POSTED BUT AVAILABLE FROM THE AUTHOR UPON REQUEST]
*Uses data from Kreutz 2015, Hyde and Marinov 2012, Azpuru et al. 2008 (not posted).

keep if first_elec==1
destring outcome_recent, replace
gen epp=0
replace epp=1 if outcome_recent==8
replace epp=1 if outcome_recent==48
replace epp=0 if outcome_recent==.
replace epp=1 if ccode==450&year==1997
replace epp=1 if ccode==581&year==2004
*2002 for all elections, and drop ndyadid for conflictid data
replace elect_obs=1 if elect_obs==1
replace elect_obs=1 if elect_obs==2
replace elect_obs=1 if elect_obs==3
replace elect_obs=1 if elect_obs==4

**International Election Observers
tab elect_obs epp, exact

**U.S. Democracy and Governance Aid Percent of Development Aid (Logged, 2-yr average)
gen aid100a=ln(aid100)

by epp, sort: sum aid100a
tab epp aid100a, exact

**Non-U.S. Democracy and Governance Aid Percent of Development Aid (Logged, 2-yr average)
gen oda100a=ln(oda100)

by epp, sort: sum oda100a
tab epp oda100a, exact

**Any Conditionality or Pressure before Elections
tab extpre2 epp, exact

**Any Conditionality before Elections
tab extcondpre2 epp, exact

**Any Pressure before Elections
tab extnoncondpre2 epp, exact


*=======Table 6.8: All Electoral Provisions and Conflict Recurrence=======*

use Matanock_Electing Peace_Agreements.dta, clear

replace allelec=. if propart==.
replace elections1=. if allelec==.
**Chadian cases with missing text were difficult to interpret on whether they had any electoral provisions (although not electoral participation provisions), so they are dropped in this analysis.**

logit failure allelec, cluster(ccode)
replace elections1=. if propart==.
replace elections1=3 if elections1==0
logit failure i.elections1, cluster(ccode)






